package com;

import com.i2p.commons.exception.I2pException;
import com.i2p.commons.mail.EmailConfig;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * email工具类
 *
 * @author swp
 * @create 2017-03-06 15:54
 **/
public class EmailUtil {

    public static boolean sendTextMail(EmailConfig mailInfo) {
        try {
            JavaMailSenderImpl mex = new JavaMailSenderImpl();
            MimeMessage mimeMessage = mex.createMimeMessage();
            MimeMessageHelper testMessageHelper = new MimeMessageHelper(mimeMessage, "UTF-8");
            Properties prop = new Properties();
            prop.put("mail.smtp.auth", "true");
            prop.put("mail.host", mailInfo.getMailServerHost());
            prop.put("mail.smtp.timeout", "25000");
            mex.setJavaMailProperties(prop);
            mex.setUsername(mailInfo.getUserName().trim());
            mex.setPassword(mailInfo.getPassword().trim());
            testMessageHelper.setFrom(new InternetAddress(mailInfo.getFromAddress(), mailInfo.getNickname()));
            testMessageHelper.setTo(mailInfo.getToAddress().trim());
            testMessageHelper.setSubject(mailInfo.getSubject());
            testMessageHelper.setText(mailInfo.getContent());
            mex.send(mimeMessage);
            return true;
        } catch (Exception var5) {
            throw new I2pException("Error Sending mail", var5);
        }
    }

    public static boolean sendHtmlMail(EmailConfig mailInfo) {
        try {
            JavaMailSenderImpl mex = new JavaMailSenderImpl();
            MimeMessage testMessage = mex.createMimeMessage();
            MimeMessageHelper testMessageHelper = new MimeMessageHelper(testMessage, "UTF-8");
            Properties prop = new Properties();
            prop.put("mail.smtp.auth", "true");
            prop.put("mail.host", mailInfo.getMailServerHost());
            prop.put("mail.smtp.timeout", "25000");
            mex.setJavaMailProperties(prop);
            mex.setUsername(mailInfo.getUserName().trim());
            mex.setPassword(mailInfo.getPassword().trim());
            testMessageHelper.setFrom(new InternetAddress(mailInfo.getFromAddress(), mailInfo.getNickname()));
            testMessageHelper.setTo(mailInfo.getToAddress().trim());
            testMessageHelper.setSubject(mailInfo.getSubject());
            testMessageHelper.setText(mailInfo.getContent(), true);
            mex.send(testMessage);
            return true;
        } catch (Exception var5) {
            throw new I2pException("Error Sending mail", var5);
        }
    }
}
